<template>
  <div class="search-page">
    <div class="search-header">
      <el-input
        v-model="searchQuery"
        placeholder="搜索照片、用户或标签"
        prefix-icon="el-icon-search"
        @keyup.enter.native="handleSearch"
        clearable>
        <el-button 
          slot="append" 
          icon="el-icon-search" 
          @click="handleSearch">搜索</el-button>
      </el-input>
      
      <div class="filter-container">
        <el-radio-group v-model="searchType" size="small" @change="handleSearch">
          <el-radio-button label="photo">照片</el-radio-button>
          <el-radio-button label="user">用户</el-radio-button>
          <el-radio-button label="tag">标签</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else-if="noResults" class="no-results">
      <el-empty description="没有找到相关结果"></el-empty>
    </div>
    
    <!-- 照片搜索结果 -->
    <div v-else-if="searchType === 'photo' && photoResults.length > 0" class="photo-results">
      <h3 class="result-title">照片搜索结果</h3>
      <div class="photo-grid">
        <div v-for="photo in photoResults" :key="photo.id" class="photo-item">
          <el-card :body-style="{ padding: '0px' }" shadow="hover">
            <div class="photo-img" @click="viewPhotoDetail(photo.id)">
              <img :src="photo.imageUrl" :alt="photo.title">
            </div>
            <div class="photo-info">
              <span class="photo-title">{{ photo.title }}</span>
              <div class="photo-stats">
                <span><i class="el-icon-view"></i> {{ photo.viewCount }}</span>
                <span><i class="el-icon-star-on"></i> {{ photo.likeCount }}</span>
              </div>
            </div>
            <div class="photo-author">
              <span @click.stop="viewAuthorDetail(photo.userId)">
                <i class="el-icon-user"></i> {{ photo.username }}
              </span>
            </div>
          </el-card>
        </div>
      </div>
    </div>
    
    <!-- 用户搜索结果 -->
    <div v-else-if="searchType === 'user' && userResults.length > 0" class="user-results">
      <h3 class="result-title">用户搜索结果</h3>
      <div class="user-list">
        <el-card v-for="user in userResults" :key="user.id" class="user-card" shadow="hover" @click.native="viewAuthorDetail(user.id)">
          <div class="user-item">
            <el-avatar :size="60" :src="user.avatar || defaultAvatar"></el-avatar>
            <div class="user-info">
              <div class="user-name">{{ user.username }}</div>
              <div class="user-meta">
                <span><i class="el-icon-picture"></i> {{ user.photoCount || 0 }} 作品</span>
                <span><i class="el-icon-star-on"></i> {{ user.likeCount || 0 }} 获赞</span>
              </div>
              <div class="user-bio">{{ user.bio || '这个用户很懒，还没有填写个人简介' }}</div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    
    <!-- 标签搜索结果 -->
    <div v-else-if="searchType === 'tag' && tagResults.length > 0" class="tag-results">
      <h3 class="result-title">标签搜索结果</h3>
      <div class="tag-list">
        <el-tag
          v-for="tag in tagResults"
          :key="tag.id"
          size="medium"
          effect="plain"
          class="tag-item"
          @click="searchByTag(tag.name)">
          {{ tag.name }} ({{ tag.count }})
        </el-tag>
      </div>
      
      <div v-if="tagPhotoResults.length > 0" class="tag-photos">
        <h4>含有标签 "{{ currentTag }}" 的照片</h4>
        <div class="photo-grid">
          <div v-for="photo in tagPhotoResults" :key="photo.id" class="photo-item">
            <el-card :body-style="{ padding: '0px' }" shadow="hover">
              <div class="photo-img" @click="viewPhotoDetail(photo.id)">
                <img :src="photo.imageUrl" :alt="photo.title">
              </div>
              <div class="photo-info">
                <span class="photo-title">{{ photo.title }}</span>
                <div class="photo-stats">
                  <span><i class="el-icon-view"></i> {{ photo.viewCount }}</span>
                  <span><i class="el-icon-star-on"></i> {{ photo.likeCount }}</span>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>
    
    <el-pagination
      v-if="total > 0"
      @current-change="handlePageChange"
      :current-page.sync="page"
      :page-size="pageSize"
      layout="prev, pager, next, jumper"
      :total="total"
      background>
    </el-pagination>
  </div>
</template>

<script>
import { formatDate } from '@/utils/date'

export default {
  name: 'Search',
  data() {
    return {
      searchQuery: '',
      searchType: 'photo',
      loading: false,
      photoResults: [],
      userResults: [],
      tagResults: [],
      tagPhotoResults: [],
      currentTag: '',
      page: 1,
      pageSize: 12,
      total: 0,
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    }
  },
  computed: {
    noResults() {
      if (this.searchType === 'photo') {
        return this.photoResults.length === 0 && !this.loading && this.searchQuery !== ''
      } else if (this.searchType === 'user') {
        return this.userResults.length === 0 && !this.loading && this.searchQuery !== ''
      } else {
        return this.tagResults.length === 0 && !this.loading && this.searchQuery !== ''
      }
    }
  },
  created() {
    // Check if there's a query parameter in the route
    const query = this.$route.query.q
    const type = this.$route.query.type
    
    if (query) {
      this.searchQuery = query
      if (type && ['photo', 'user', 'tag'].includes(type)) {
        this.searchType = type
      }
      this.handleSearch()
    }
  },
  methods: {
    handleSearch() {
      if (!this.searchQuery.trim()) return
      
      this.page = 1
      this.tagPhotoResults = []
      this.currentTag = ''
      
      // Update URL with search parameters
      this.$router.replace({
        query: { 
          q: this.searchQuery,
          type: this.searchType
        }
      })
      
      if (this.searchType === 'photo') {
        this.searchPhotos()
      } else if (this.searchType === 'user') {
        this.searchUsers()
      } else {
        this.searchTags()
      }
    },
    async searchPhotos() {
      this.loading = true
      try {
        const res = await this.$http.get('/photos/search', {
          params: {
            keyword: this.searchQuery,
            page: this.page,
            pageSize: this.pageSize
          }
        })
        
        if (res.data.code === 1) {
          this.photoResults = res.data.data.records || []
          this.total = res.data.data.total || 0
        } else {
          this.$message.error(res.data.msg || '搜索失败')
        }
      } catch (error) {
        console.error('搜索照片失败', error)
        this.$message.error('搜索照片失败')
      } finally {
        this.loading = false
      }
    },
    async searchUsers() {
      this.loading = true
      try {
        const res = await this.$http.get('/users/search', {
          params: {
            keyword: this.searchQuery,
            page: this.page,
            pageSize: this.pageSize
          }
        })
        
        if (res.data.code === 1) {
          this.userResults = res.data.data.records || []
          this.total = res.data.data.total || 0
        } else {
          this.$message.error(res.data.msg || '搜索失败')
        }
      } catch (error) {
        console.error('搜索用户失败', error)
        this.$message.error('搜索用户失败')
      } finally {
        this.loading = false
      }
    },
    async searchTags() {
      this.loading = true
      try {
        const res = await this.$http.get('/tags/search', {
          params: {
            keyword: this.searchQuery,
            page: this.page,
            pageSize: this.pageSize
          }
        })
        
        if (res.data.code === 1) {
          this.tagResults = res.data.data.records || []
          this.total = res.data.data.total || 0
        } else {
          this.$message.error(res.data.msg || '搜索失败')
        }
      } catch (error) {
        console.error('搜索标签失败', error)
        this.$message.error('搜索标签失败')
      } finally {
        this.loading = false
      }
    },
    async searchByTag(tagName) {
      this.currentTag = tagName
      try {
        const res = await this.$http.get('/photos/tags', {
          params: {
            tag: tagName,
            page: 1,
            pageSize: 8
          }
        })
        
        if (res.data.code === 1) {
          this.tagPhotoResults = res.data.data.records || []
        } else {
          this.$message.error(res.data.msg || '获取标签照片失败')
        }
      } catch (error) {
        console.error('获取标签照片失败', error)
        this.$message.error('获取标签照片失败')
      }
    },
    handlePageChange(page) {
      this.page = page
      if (this.searchType === 'photo') {
        this.searchPhotos()
      } else if (this.searchType === 'user') {
        this.searchUsers()
      } else {
        this.searchTags()
      }
    },
    viewPhotoDetail(photoId) {
      this.$router.push(`/photos/${photoId}`)
    },
    viewAuthorDetail(userId) {
      this.$router.push(`/author/${userId}`)
    },
    formatDate
  }
}
</script>

<style scoped>
.search-page {
  padding: 20px;
}

.search-header {
  margin-bottom: 20px;
}

.filter-container {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.loading-container {
  padding: 20px 0;
}

.result-title {
  margin-bottom: 20px;
  font-size: 18px;
  color: #303133;
}

.no-results {
  margin: 50px 0;
  text-align: center;
}

/* Photo results styles */
.photo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.photo-img {
  height: 180px;
  overflow: hidden;
  cursor: pointer;
}

.photo-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.photo-img:hover img {
  transform: scale(1.05);
}

.photo-info {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.photo-title {
  font-size: 14px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 150px;
}

.photo-stats {
  display: flex;
  gap: 10px;
  font-size: 12px;
  color: #909399;
}

.photo-author {
  padding: 0 10px 10px;
  font-size: 12px;
  color: #409EFF;
  cursor: pointer;
}

.photo-author:hover {
  text-decoration: underline;
}

/* User results styles */
.user-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.user-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.user-card:hover {
  transform: translateY(-3px);
}

.user-item {
  display: flex;
  align-items: center;
}

.user-info {
  margin-left: 20px;
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.user-meta {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
  display: flex;
  gap: 15px;
}

.user-bio {
  font-size: 13px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* Tag results styles */
.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 30px;
}

.tag-item {
  cursor: pointer;
  transition: all 0.2s;
}

.tag-item:hover {
  color: #409EFF;
  border-color: #409EFF;
}

.tag-photos {
  margin-top: 20px;
}

.tag-photos h4 {
  margin-bottom: 15px;
  color: #606266;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .photo-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
  
  .user-item {
    flex-direction: column;
    text-align: center;
  }
  
  .user-info {
    margin-left: 0;
    margin-top: 10px;
  }
  
  .user-meta {
    justify-content: center;
  }
}
</style> 